<template>
  <div>
  <!-----进货----->
    <el-page-header @back="back()" content="进货详情页面" style="margin-bottom: 10px;"/>
      <el-row :gutter="20">
        <el-col :span="8"><div class="grid-content bg-purple">进货单编号:</div></el-col>
        <el-col :span="16"><div class="grid-content bg-purple">
          {{receipt_no}}
        </div></el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="grid-content bg-purple">
          供货商:
            <el-select
              v-model="supplier"
              filterable
              remote
              :disabled="!editing"
              :remote-method="findByName"
              placeholder="输入供货商"
              :loading="loading">
              <el-option
                v-for="item in suppliers"
                :key="supplier.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
        </div>
        </el-col>
        <el-col :span="8"><div class="grid-content bg-purple">供货商地址</div></el-col>
        <el-col :span="4"><div class="grid-content bg-purple">日期:</div></el-col>
        <el-col :span="4"><div class="grid-content bg-purple">{{date}}</div></el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
        <div class="grid-content bg-purple">
          <el-table
            :data="goodList.slice((currentPage-1)*pagesize,currentPage*pagesize)"
            border
            max-height="40vh"
            height="40vh"
            show-summary
            :summary-method="getSumNum"
            style="width: 85vw;top: 0px">
            <el-table-column
              label="商品名称"
              class-name="name"
              align="center"
              prop="name">
            </el-table-column>
            <el-table-column
              label="商品条码"
              align="center"
              class-name="barcode"
              prop="barcode">
            </el-table-column>
            <el-table-column
              label="进价"
              class-name="cost"
              align="center"
              prop="cost">
              <template slot-scope="scope">
                <el-input :disabled="!editing" v-model=scope.row.cost @input="setTotal(scope.row.name)"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              label="数量"
              class-name="num"
              align="center"
              prop="num">
              <template slot-scope="scope">
                <el-input :disabled="!editing" v-model=scope.row.num @input="setTotal(scope.row.name)"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              label="总额"
              class-name="total"
              align="center"
              prop="totalcost">
            </el-table-column>
          </el-table>
        </div>
      </el-col>
        <el-button :class="[editing?'':'btn-hidden']" type="primary" @click="addGoods()">添加商品</el-button>
        <select-goods ref="select_goods"></select-goods>
      </el-row>
    <el-row :gutter="20">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 40]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="goodList.length">
      </el-pagination>
    </el-row>
      <el-row :gutter="20">
        <el-col :span="8"><div class="grid-content bg-purple">进货单位</div></el-col>
        <el-col :span="8"><div class="grid-content bg-purple">进货地址</div></el-col>
        <el-col :span="8"><div class="grid-content bg-purple">负责人</div></el-col>
      </el-row>
    <el-button type="primary" :class="[editing?'':'btn-hidden']" @click="onSubmit">保存</el-button>
    <el-button @click="cancel" :class="[editing?'':'btn-hidden']">取消</el-button>
  </div>
</template>

<script>
    import bus from "../../../bus";
    import SelectGoods from "./SelectGoods";
    export default {
        name: "Purchase",
      components: { SelectGoods},
      data(){
        return {
          editing:true,
          currentPage:1, //初始页
          pagesize:5,    //    每页的数据
          receipt_no:'JH'+this._func.getId(),
          date:this._date.getDate(1),
          loading:false,
          supplier:'',
          goodList:[],
          totalcost:0,
          suppliers:[],
          rules:{
            num:[{required:true,message:'数量不能为空',trigger:'blur'}],
            unitPrice:[{required:true,message:'单价不能为空',trigger:'blur'}]
          }
        }
      },
      methods:{
          back(){
            this.$router.back();
          },
        // 初始页currentPage、初始每页数据数pagesize和数据data
        handleSizeChange: function (size) {
          this.pagesize = size;
        },
        handleCurrentChange: function(currentPage){
          this.currentPage = currentPage;
        },
        save(){
          this.$refs['form'].validate((valid)=>{
            if(valid){
              console.log(1)
              }
          })
        },
        cancel(){
          this.dialogFormVisible=false;
          this.$router.go(-1);
        },
        setTotal(name){
          let good=this.goodList.find(item=>item.name==name);
          good.totalcost=good.cost*good.num;
        },
        addGoods(){
          this.$refs.select_goods.dialogFormVisible=true;
        },
        //远程搜索供应商
        findByName(query){
          this.loading=true;
          this._get.findSupplierByName(query).then(resp=>{
            this.suppliers=resp;
            this.loading=false;
          })
        },
        loadGoods(barcodesList){
          var _this=this;
          _this.goodList=[]
          this.$axios.post('/goods/goodsList',barcodesList)
            .then(resp => {
              if (resp && resp.status === 200) {
                resp.data.forEach((good)=>{
                  var item={
                    name:'',
                    barcode:'',
                    num:0,
                    cost:0,
                    totalcost:0,
                    //unit:'',
                    good:''
                  }
                  item.name=good.name;
                  item.barcode=good.barcode;
                  item.cost=good.cost;
                  //item.unit=good.unit.unit;
                  item.good=good;
                  _this.goodList.push(item)
                })
                //console.log('******Purchase-loadGoods*******')
                //console.log(JSON.stringify(_this.goodList))
              }
          })
        },
        getSumNum(param){
          const { columns, data } = param;
          const sums = [];
          columns.forEach((column, index) => {
            if (index === 0) {
              sums[index] = '合计';
              return;
            }
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
              if(column.className=='num' || column.className=='total'){
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr);
                  if (!isNaN(value)) {
                    return prev + curr;
                  } else {
                    return prev;
                  }
                }, 0);
                if(column.className=='total'){
                  this.totalcost=sums[index];
                }
              }
            } else {
              sums[index] = 'N/A';
            }
          });

          return sums;
        },
        //获取商品进货列表
        getList(){
          console.log('****Purchase-getList*****')
          var temp=[];
          this.goodList.forEach(good=>{
            var data={
              receipt_no: this.receipt_no,
              barcode:'',
              good_name:'',
              //good:'',
              cost:0.0,
              num:0,
              totalcost:0.0,
              date:this._date.getDate(1)
            }
            data.barcode=good.barcode;
            data.cost=good.cost;
            data.totalcost=good.totalcost;
            data.num=good.num;
            data.good_name=good.name;
            //data.good=good.good;
            temp.push(data)
            console.log('good:')
            console.log(JSON.stringify(good))
          })
          console.log(JSON.stringify(temp))
          return temp
        },
        //提交
        onSubmit(){
          this.$axios
            .post('/receipt/add', this.getList()).then(
            this.$axios.post('/receipt/receiptInfo/add',{
              receipt_no:this.receipt_no,
              date:this.date,
              totalcost:this.totalcost,
              supplier:this.supplier,
            }))
            .then(resp => {
              if (resp && resp.status === 200) {
                //this.dialogFormVisible = false
                bus.$emit('loadGoods');
                this.editing=false;
                this.$message({
                  message:this.receipt_no+'添加成功',
                  type:'success'
                })
              }}
            )
        },

      },
      mounted(){
          bus.$on('selectGoods',(data)=>{
            this.loadGoods(data)
          })
      }
    }
</script>

<style scoped>
  .btn-hidden{
    display: none;
  }
  .el-row {
    margin-bottom: 20px;
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 4px;
    min-height: 36px;
    text-align: center;
  }
  .row-bg {
    padding: 0px 0;
    background-color: #f9fafc;
  }

</style>
<style>
.el-page-header{
  margin-bottom: 100px;
}
</style>
